package 我的Java学习_算法基础.day_03;

import static 我的Java学习_算法基础.day_01.唯一成对的数.printArray;

public class _046_构造小顶堆_递归 {
    public static void main(String[] args) {
        int[] a = {8, 5, 10, 7, 4, 9, 7, 2, 23};
        makeMinHeapRecursive(a);
        printArray(a);
    }

    public static void makeMinHeapRecursive(int[] array) {
        int n = array.length;
        for (int i = n / 2 - 1; i >= 0; i--) {
            minHeapFixDownRecursive(array, i, n);
        }
    }

    private static void minHeapFixDownRecursive(int[] array, int i, int length) {
        //左右孩子
        int left = 2*i+1;
        int right = 2*i+2;
        if(left>=length){
            return;
        }
        int min = left;
        if(right>=length){
            min = left;
        }else if(array[right]<array[left]){
            min = right;
        }
        if(array[i]<=array[min]){
            return;
        }
        int temp = array[i];
        array[i] = array[min];
        array[min] = temp;
        minHeapFixDownRecursive(array,min,length);
    }
}
